<template>
  <div>
    <!-- 添加或修改资产清单表对话框 -->
    <el-dialog ref="editDialog" v-model="openFlag" title="添加入库单" style="max-height: 86vh; width: 70vw;" append-to-body>
      <el-scrollbar max-height="65vh">
        <div class="ui_el_dialog_body">
          <el-form ref="form" :model="formData" :rules="rules" label-width="108px" class="dialog-form-two">
            <el-row>
              <el-text class="from-title-style">基本信息</el-text>
            </el-row>
            <el-row>
              <el-col :span="8">
                <el-form-item label="入库处理时间" prop="remark">
                  <date-editor v-model="formData.handleTime" type="date" placeholder="入库处理时间" :clearable="true" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="备注" prop="remark">
                  <el-input type="textarea" v-model="formData.remark" placeholder="请输入备注" :rows="3" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="8">
                <el-text class="from-title-style">资产列表</el-text>
              </el-col>
              <el-col :span="8" :offset="8">
                <div style="width: 100%; text-align: right;">
                  <el-button :type="primary" text style="color: #005bf5;" @click="handleAdd">新增</el-button>
                </div>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <vxe-table ref="tableRef" height="auto" style="height: 40vh;" :data="tableData.list"
                  :edit-rules="validRules" keep-source border stripe :scroll-y="{ enabled: true, offset: 10 }">
                  <vxe-column type="seq" width="70"></vxe-column>

                  <vxe-column field="assetCode" title="资产编码" :min-width="150">
                    <template #default="{ row }">
                      <el-input v-model="row.assetCode" placeholder="自动生成"></el-input>
                    </template>
                  </vxe-column>

                  <vxe-column field="name" title="资产名称" :min-width="200">
                    <template #default="{ row }">
                      <el-input v-model="row.name"></el-input>
                    </template>
                  </vxe-column>

                  <vxe-column field="categoryId" title="资产分类" :min-width="150">
                    <template #default="{ row }">
                      <category-select v-model="row.categoryId"></category-select>
                    </template>
                  </vxe-column>
                  <vxe-column field="admin" title="管理员" :min-width="150">
                    <template #default="{ row }">
                      <user-select
                          v-model.trim="row.company"
                          v-model:name="row.adminName"
                          v-model:company-id="row.companyId"
                          v-model:company-name="row.companyName"
                          placeholder="请选择管理员"
                      ></user-select>
                    </template>
                  </vxe-column>

                  <vxe-column field="company" title="所在公司" :min-width="150">
                    <template #default="{ row }">
                      <el-input v-model="row.companyName" disabled="true"></el-input>
                    </template>
                  </vxe-column>


                  <vxe-column field="location" title="所在仓库" :min-width="150">
                    <template #default="{ row }">
                      <warehouse-select v-model="row.location"></warehouse-select>
                    </template>
                  </vxe-column>

                  <vxe-column field="brand" title="品牌" :min-width="150">
                    <template #default="{ row }">
                      <el-input v-model="row.brand"></el-input>
                    </template>
                  </vxe-column>

                  <vxe-column field="model" title="型号" :min-width="150">
                    <template #default="{ row }">
                      <el-input v-model="row.model"></el-input>
                    </template>
                  </vxe-column>

                  <vxe-column field="purchaseMethod" title="购置方式" :min-width="150">
                    <template #default="{ row }">
                      <el-input v-model="row.purchaseMethod"></el-input>
                    </template>
                  </vxe-column>

                  <vxe-column field="purchaseDate" title="购置时间" :min-width="150">
                    <template #default="{ row }">
                      <el-date-picker v-model="row.purchaseDate" type="date" style="width: 100%;"></el-date-picker>
                    </template>
                  </vxe-column>

                  <vxe-column field="purchaseAmount" title="购置金额" :min-width="150">
                    <template #default="{ row }">
                      <el-input v-model="row.purchaseAmount"></el-input>
                    </template>
                  </vxe-column>

                  <vxe-column field="user" title="使用人" :min-width="150">
                    <template #default="{ row }">
                      <user-select v-model="row.userId" v-model:name="row.userName" placeholder="请选择使用人"></user-select>
                    </template>
                  </vxe-column>

                  <vxe-column field="department" title="使用部门" :min-width="150">
                    <template #default="{ row }">
                      <el-input v-model="row.department"></el-input>
                    </template>
                  </vxe-column>

                  <vxe-column field="usageDuration" title="使用期限(月)" :min-width="150">
                    <template #default="{ row }">
                      <el-input v-model="row.usageDuration"></el-input>
                    </template>
                  </vxe-column>

                  <vxe-column field="borrowDate" title="领用时间" :min-width="150">
                    <template #default="{ row }">
                      <el-date-picker v-model="row.borrowDate" type="date" style="width: 100%;"></el-date-picker>
                    </template>
                  </vxe-column>

                  <vxe-column field="unit" title="计量单位" :min-width="150">
                    <template #default="{ row }">
                      <el-input v-model="row.unit"></el-input>
                    </template>
                  </vxe-column>

                  <vxe-column field="supplier" title="供应商" :min-width="150">
                    <template #default="{ row }">
                      <el-input v-model="row.supplier"></el-input>
                    </template>
                  </vxe-column>

                  <vxe-column field="supplierContact" title="供应商联系人" :min-width="150">
                    <template #default="{ row }">
                      <el-input v-model="row.supplierContact"></el-input>
                    </template>
                  </vxe-column>

                  <vxe-column field="contactNumber" title="联系电话" :min-width="150">
                    <template #default="{ row }">
                      <el-input v-model="row.contactNumber"></el-input>
                    </template>
                  </vxe-column>

                  <vxe-column field="personInCharge" title="负责人" :min-width="150">
                    <template #default="{ row }">
                      <user-select v-model="row.personInCharge" v-model:name="row.personInCharge"></user-select>
                    </template>
                  </vxe-column>

                  <vxe-column field="maintenanceDueDate" title="保养到期时间" :min-width="150">
                    <template #default="{ row }">
                      <el-date-picker v-model="row.maintenanceDueDate" type="date"
                        style="width: 100%;"></el-date-picker>
                    </template>
                  </vxe-column>

                  <vxe-column field="depreciationPeriod" title="折旧期限(月)" :min-width="150">
                    <template #default="{ row }">
                      <el-input v-model="row.depreciationPeriod"></el-input>
                    </template>
                  </vxe-column>

                  <vxe-column field="maintenanceDescription" title="保养说明" :min-width="150">
                    <template #default="{ row }">
                      <el-input v-model="row.maintenanceDescription"></el-input>
                    </template>
                  </vxe-column>

                  <vxe-column title="操作" width="100">
                    <template #default="{ row }">
                      <el-button link @click="handleDelete(row)">删除</el-button>
                    </template>
                  </vxe-column>
                </vxe-table>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </el-scrollbar>
      <template #footer>
        <div class="ui_el_dialog_footer">
          <el-button @click="close">取消</el-button>
          <el-button @click="save">保存草稿</el-button>
          <el-button type="primary" style="color: #fff; background-color: #005bf5;" @click="sub">提交</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>

import api from "@/api/asset/apply.js";
import { VxeUI } from 'vxe-table';
import useAssetCategoryStore from '@/store/modules/assetCategory';
import treeUtil from '@/utils/tree.js';
import { reactive, ref, onMounted, getCurrentInstance, defineEmits, defineProps, defineExpose } from 'vue';
import CategorySelect from "@/components/Asset/CategorySelect.vue";
import DateEditor from "@/components/Common/DateEditor.vue";
import UserSelect from "@/components/User/UserSelect.vue";
import WarehouseSelect from "@/components/Warehouse/WarehouseSelect.vue";

const proxy = getCurrentInstance();
const assetCategoryStore = useAssetCategoryStore();

const regionEditRender = reactive({
  name: 'VxeTreeSelect',
  options: []
});

async function init() {
  const categoryList = await assetCategoryStore.getList();
  categoryList.forEach(item => {
    item.value = item.id;
    item.label = item.name;
  });
  const treeData = treeUtil.convertToTree(categoryList);
  regionEditRender.options = treeData;
}

const emit = defineEmits(['sub']);
const tableRef = ref();

const props = defineProps({
  applyType: {
    type: String,
    required: true,
  },
  applyTypeName: {
    type: String,
    required: true,
  },
});

const isEdit = ref(false);
const rules = {
  name: {
    required: true, message: '不能为空'
  }
};

const validRules = ref({
  name: [
    { required: true, message: '必须填写' }
  ]
});

const applyDataInit = {
  id: null,
  applyType: props.applyType,
  applyTypeName: props.applyTypeName,
  remark: null
};

const applyData = reactive(applyDataInit);
const formDataInit = {
  handleTime: null,
  remark: null
};
const tableData = reactive({
  loading: false,
  list: [],
});

const openFlag = ref(false);
const form = ref();
const value2 = ref(null);

const emptyItem = {
  number: null,
  num: 1,
  name: '',
  categoryId: ''
};

const formData = reactive(formDataInit);

function reset() {
  Object.assign(formData, formDataInit);
  tableData.list = [];
}

function open(row) {
  openFlag.value = true;
  reset();
  if (row) {
    api.detail(row).then(response => {
      Object.assign(applyData, response);
      let resFormData = response.formData;
      if (resFormData) {
        if (typeof resFormData === 'string') {
          resFormData = JSON.parse(resFormData);
        }
        Object.assign(formData, resFormData);
      }
      let relItems = formData.items;
      if (!relItems) {
        relItems = [];
      }
      tableData.list = relItems;
    });
    isEdit.value = true;
  } else {
    isEdit.value = false;
  }
}

function close() {
  openFlag.value = false;
}
let clickCount = 0;
function handleAdd() {
  clickCount += 1;
  tableData.list.push({ ...emptyItem });
}

async function handleDelete(row) {
  const $table = tableRef.value;
  if ($table) {
    const type = await VxeUI.modal.confirm('您确定要删除该数据?');
    if (type === 'confirm') {
      const index = tableData.list.findIndex(item => item === row);
      tableData.list.splice(index, 1);
    }
  }
}

function getParams() {
  const apply = { ...applyData };
  apply.applyType = props.applyType;
  apply.applyTypeName = props.applyTypeName;
  const items = tableData.list.filter(item=> {
    return item.name;
  });
  formData.items = items;
  formData.num = items.length ? items.length : 0;

  apply.formData = JSON.stringify(formData);
  apply.dateTime = value2.value;
  return {
    edit: isEdit.value,
    apply: apply
  };
}

async function check() {
  if (!tableData.list.length) {
    VxeUI.modal.message({ status: 'error', content: '入库条目为空，请填写你要入库的条目' });
    return false;
  }
  const $table = tableRef.value;
  const errMap = await $table.validate(true);
  if (errMap) {
    return false;
  }
  return true;
}

/** 保存 */
async function save() {
  let checkResult = await check();
  if (!checkResult) {
    return false;
  }
  api.save(getParams()).then(response => {
    emit("sub");
    close();
  });
}

async function sub() {
  const checkRes = await check();
  if (!checkRes) {
    return;
  }
  api.saveAndSub(getParams()).then(response => {
    emit("sub");
    close();
  });
}

onMounted(() => {
  init();
});

defineExpose({
  open
});
</script>

<style lang="scss">

</style>